import { getToken } from '@/utils/auth'
const sha256 = require('js-sha256').sha256

/**
 * author：郭计腾
 * post请求加密算法
 */
const whiteList = ['login'] // 请求白名单,如果存在的话 则不加密 /admin/user/getToken
export function resPost(data, obj) {
  const config = data
  if (whiteList.indexOf(config.url) === -1) {
    const sjzfc = randomString()
    let NEWAESlist = ''
    if (localStorage.getItem('NEWAES') != null && localStorage.getItem('NEWAES') !== undefined) {
      NEWAESlist = localStorage.getItem('NEWAES').split(',')
    }
    let encyStr = ''
    if (obj != null) {
      const ascObj = objKeySort(obj) // 把对象排序
      var count = 0 // 对象属性的个数
      for (const i in ascObj) {
        if (ascObj.hasOwnProperty(i)) {
          count++
        }
      }
      let index = 0
      for (const key in ascObj) {
        index += 1
        encyStr += key + '=' + ascObj[key] || ''
        if (index !== count) {
          encyStr += '|'
        }
      }
    }
    if (!getToken()) {
      NEWAESlist = ''
    }
    /**
     * 保证所有接口都必须校验签名，由于token过期后后端获取不到对应的key和iv导致验签失败，所以增加一个不带key和iv的签名
     */
    // 带key和iv的签名
    const bwqm1 = encyStr + ':' + (getToken() || '') + ':' + sjzfc + ':' + NEWAESlist || ''
    // 不带key和iv的签名
    const bwqm2 = encyStr + ':' + (getToken() || '') + ':' + sjzfc + ':' + ''
    config.headers['ttsxyhcs'] = getToken() || ''
    config.headers['ttsxsjzc'] = sjzfc
    config.headers['ttsxbwqm'] = sha256(bwqm1) + ',' + sha256(bwqm2)
    if (process.env.NODE_ENV === 'development') {
      config.headers['ttsxbid'] = 1
    }
  }
  return config
}

/**
 *  响应时判断是否被篡改
 * @param {*} data
 */
export function getRes(data) {
  if (localStorage.getItem('NEWAES') == null || localStorage.getItem('NEWAES').length === 0) {
    return true
  }
  var NEWAESlist = localStorage.getItem('NEWAES')

  const sjzfc = data.config.headers.ttsxsjzc
  let NEWKEY = NEWAESlist
  const sign = data.headers.ttsxbwqm
  const ascStr = data.data

  if (data.headers.ttsxmynk) {
    NEWKEY = data.headers.ttsxmynk
  }
  const allStr = ascStr + '|' + sjzfc + '|' + NEWKEY
  const codeStr = sha256(allStr)
  if (codeStr === sign) {
    return true
  }
  return false
}

// 生成随机字符串
function randomString(len) {
  len = len || 32
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = chars.length
  var pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

// 随机生成16进制数据
export function randomHexadecimal(len) {
  len = len || 32
  var Hexadecimal = ''
  for (let i = 0; i <= len; i++) {
    var tmp = Math.ceil(Math.random() * 15)
    if (tmp > 9) {
      switch (tmp) {
        case 10:
          Hexadecimal += 'a'
          break
        case 11:
          Hexadecimal += 'b'
          break
        case 12:
          Hexadecimal += 'c'
          break
        case 13:
          Hexadecimal += 'd'
          break
        case 14:
          Hexadecimal += 'e'
          break
        case 15:
          Hexadecimal += 'f'
          break
      }
    } else {
      Hexadecimal += tmp
    }
  }
  return Hexadecimal
}

function objKeySort(obj) {
  // 排序的函数
  var newkey = Object.keys(obj).sort() // 先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
  var newObj = {} // 创建一个新的对象，用于存放排好序的键值对
  for (var i = 0; i < newkey.length; i++) {
    // 遍历newkey数组
    newObj[newkey[i]] = obj[newkey[i]] // 向新创建的对象中按照排好的顺序依次增加键值对
  }
  return newObj // 返回排好序的新对象
}
